<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <div class="profile-header">
        <h1>个人资料</h1>
      </div>
      
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基本信息" name="basic">
          <el-form
            ref="basicFormRef"
            :model="basicForm"
            :rules="basicRules"
            label-width="100px"
            class="profile-form"
          >
            <el-form-item label="头像">
              <div class="avatar-uploader">
                <el-avatar :size="100" :src="basicForm.avatar || defaultAvatar" />
                <el-button size="small" type="primary" class="avatar-upload-btn">更换头像</el-button>
              </div>
            </el-form-item>
            
            <el-form-item label="用户名" prop="username">
              <el-input v-model="basicForm.username" disabled />
            </el-form-item>
            
            <el-form-item label="姓名" prop="name">
              <el-input v-model="basicForm.name" />
            </el-form-item>
            
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="basicForm.email" />
            </el-form-item>
            
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="basicForm.phone" />
            </el-form-item>
            
            <el-form-item label="职位" prop="position">
              <el-input v-model="basicForm.position" />
            </el-form-item>
            
            <el-form-item label="部门" prop="department">
              <el-input v-model="basicForm.department" />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="updateBasicInfo">保存修改</el-button>
              <el-button @click="resetBasicForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="修改密码" name="password">
          <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="100px"
            class="profile-form"
          >
            <el-form-item label="当前密码" prop="currentPassword">
              <el-input v-model="passwordForm.currentPassword" type="password" show-password />
            </el-form-item>
            
            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="passwordForm.newPassword" type="password" show-password />
            </el-form-item>
            
            <el-form-item label="确认新密码" prop="confirmPassword">
              <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="updatePassword">更新密码</el-button>
              <el-button @click="resetPasswordForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="通知设置" name="notifications">
          <el-form
            ref="notificationFormRef"
            :model="notificationForm"
            label-width="200px"
            class="profile-form"
          >
            <el-form-item label="任务分配通知">
              <el-switch v-model="notificationForm.taskAssignment" />
            </el-form-item>
            
            <el-form-item label="任务截止日期提醒">
              <el-switch v-model="notificationForm.taskDueDate" />
            </el-form-item>
            
            <el-form-item label="项目更新通知">
              <el-switch v-model="notificationForm.projectUpdates" />
            </el-form-item>
            
            <el-form-item label="系统公告">
              <el-switch v-model="notificationForm.systemAnnouncements" />
            </el-form-item>
            
            <el-form-item label="邮件通知">
              <el-switch v-model="notificationForm.emailNotifications" />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="updateNotificationSettings">保存设置</el-button>
              <el-button @click="resetNotificationForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="我的任务" name="tasks">
          <div class="tasks-header">
            <el-select v-model="taskFilter" placeholder="任务状态" style="width: 150px;">
              <el-option label="全部" value="" />
              <el-option label="未开始" value="未开始" />
              <el-option label="进行中" value="进行中" />
              <el-option label="已完成" value="已完成" />
              <el-option label="已暂停" value="已暂停" />
            </el-select>
          </div>
          
          <el-table
            v-loading="tasksLoading"
            :data="filteredTasks"
            style="width: 100%"
          >
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="name" label="任务名称" min-width="150" show-overflow-tooltip />
            <el-table-column prop="project_name" label="所属项目" min-width="150" show-overflow-tooltip />
            <el-table-column prop="priority" label="优先级" width="100">
              <template #default="scope">
                <el-tag :type="getPriorityType(scope.row.priority)">{{ scope.row.priority }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="due_date" label="截止日期" width="120" />
            <el-table-column prop="progress" label="进度" width="180">
              <template #default="scope">
                <el-progress :percentage="scope.row.progress" :status="getProgressStatus(scope.row.progress)" />
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="活动日志" name="activity">
          <el-timeline>
            <el-timeline-item
              v-for="(activity, index) in activities"
              :key="index"
              :timestamp="activity.timestamp"
              :type="activity.type"
              :color="activity.color"
            >
              {{ activity.content }}
            </el-timeline-item>
          </el-timeline>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
// import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'

export default {
  name: 'ProfileView',
  setup() {
    // const store = useStore()
    const activeTab = ref('basic')
    const basicFormRef = ref(null)
    const passwordFormRef = ref(null)
    const notificationFormRef = ref(null)
    const tasksLoading = ref(false)
    const taskFilter = ref('')
    const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
    
    // 基本信息表单
    const basicForm = reactive({
      username: 'admin',
      name: '管理员',
      email: 'admin@example.com',
      phone: '13800138000',
      position: '项目经理',
      department: '技术部',
      avatar: ''
    })
    
    // 基本信息验证规则
    const basicRules = {
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ],
      position: [
        { required: true, message: '请输入职位', trigger: 'blur' }
      ],
      department: [
        { required: true, message: '请输入部门', trigger: 'blur' }
      ]
    }
    
    // 密码表单
    const passwordForm = reactive({
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
    
    // 密码验证规则
    const passwordRules = {
      currentPassword: [
        { required: true, message: '请输入当前密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请再次输入新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== passwordForm.newPassword) {
              callback(new Error('两次输入密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }
    
    // 通知设置表单
    const notificationForm = reactive({
      taskAssignment: true,
      taskDueDate: true,
      projectUpdates: true,
      systemAnnouncements: true,
      emailNotifications: false
    })
    
    // 模拟任务数据
    const tasks = ref([
      {
        id: 1,
        name: '需求分析',
        project_id: 1,
        project_name: '企业官网重构项目',
        assignee: '管理员',
        priority: '高',
        status: '已完成',
        due_date: '2023-01-25',
        progress: 100
      },
      {
        id: 6,
        name: '需求调研',
        project_id: 2,
        project_name: '移动应用开发',
        assignee: '管理员',
        priority: '高',
        status: '已完成',
        due_date: '2023-02-10',
        progress: 100
      },
      {
        id: 11,
        name: '项目计划制定',
        project_id: 1,
        project_name: '企业官网重构项目',
        assignee: '管理员',
        priority: '中',
        status: '进行中',
        due_date: '2023-03-30',
        progress: 60
      },
      {
        id: 12,
        name: '资源分配',
        project_id: 2,
        project_name: '移动应用开发',
        assignee: '管理员',
        priority: '中',
        status: '未开始',
        due_date: '2023-04-05',
        progress: 0
      }
    ])
    
    // 过滤后的任务
    const filteredTasks = computed(() => {
      if (!taskFilter.value) {
        return tasks.value
      }
      return tasks.value.filter(task => task.status === taskFilter.value)
    })
    
    // 模拟活动日志
    const activities = ref([
      {
        content: '完成了任务 "需求调研"',
        timestamp: '2023-02-10 15:30',
        type: 'success',
        color: '#67C23A'
      },
      {
        content: '更新了任务 "项目计划制定" 的进度为 60%',
        timestamp: '2023-02-25 10:15',
        type: 'primary',
        color: '#409EFF'
      },
      {
        content: '创建了新任务 "资源分配"',
        timestamp: '2023-02-20 09:45',
        type: 'info',
        color: '#909399'
      },
      {
        content: '完成了任务 "需求分析"',
        timestamp: '2023-01-25 16:20',
        type: 'success',
        color: '#67C23A'
      },
      {
        content: '加入了项目 "移动应用开发"',
        timestamp: '2023-01-15 11:30',
        type: 'warning',
        color: '#E6A23C'
      },
      {
        content: '更新了个人资料',
        timestamp: '2023-01-10 14:50',
        type: 'info',
        color: '#909399'
      }
    ])
    
    // 更新基本信息
    const updateBasicInfo = () => {
      basicFormRef.value.validate(valid => {
        if (valid) {
          // 实际项目中应该调用API更新用户信息
          // store.dispatch('user/updateProfile', basicForm)
          ElMessage.success('个人资料更新成功')
        }
      })
    }
    
    // 重置基本信息表单
    const resetBasicForm = () => {
      basicFormRef.value.resetFields()
    }
    
    // 更新密码
    const updatePassword = () => {
      passwordFormRef.value.validate(valid => {
        if (valid) {
          // 实际项目中应该调用API更新密码
          // store.dispatch('user/updatePassword', {
          //   oldPassword: passwordForm.currentPassword,
          //   newPassword: passwordForm.newPassword
          // })
          ElMessage.success('密码更新成功')
          resetPasswordForm()
        }
      })
    }
    
    // 重置密码表单
    const resetPasswordForm = () => {
      passwordFormRef.value.resetFields()
    }
    
    // 更新通知设置
    const updateNotificationSettings = () => {
      // 实际项目中应该调用API更新通知设置
      // store.dispatch('user/updateNotificationSettings', notificationForm)
      ElMessage.success('通知设置更新成功')
    }
    
    // 重置通知设置表单
    const resetNotificationForm = () => {
      notificationFormRef.value.resetFields()
    }
    
    // 获取任务列表
    const fetchTasks = () => {
      tasksLoading.value = true
      // 实际项目中应该从API获取数据
      // store.dispatch('task/getUserTasks').then(response => {
      //   tasks.value = response.data
      //   tasksLoading.value = false
      // })
      
      // 模拟API请求延迟
      setTimeout(() => {
        tasksLoading.value = false
      }, 500)
    }
    
    // 获取状态对应的类型
    const getStatusType = (status) => {
      const statusMap = {
        '未开始': 'info',
        '进行中': 'primary',
        '已完成': 'success',
        '已暂停': 'warning'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取优先级对应的类型
    const getPriorityType = (priority) => {
      const priorityMap = {
        '低': 'info',
        '中': 'warning',
        '高': 'danger',
        '紧急': 'danger'
      }
      return priorityMap[priority] || 'info'
    }
    
    // 获取进度对应的状态
    const getProgressStatus = (progress) => {
      if (progress >= 100) return 'success'
      if (progress >= 80) return 'success'
      if (progress >= 50) return ''
      if (progress >= 20) return 'warning'
      return 'exception'
    }
    
    onMounted(() => {
      // 获取用户信息
      // const userInfo = store.getters['user/userInfo']
      // Object.assign(basicForm, userInfo)
      
      // 获取任务列表
      fetchTasks()
    })
    
    return {
      activeTab,
      basicFormRef,
      passwordFormRef,
      notificationFormRef,
      basicForm,
      passwordForm,
      notificationForm,
      basicRules,
      passwordRules,
      defaultAvatar,
      tasks,
      filteredTasks,
      taskFilter,
      tasksLoading,
      activities,
      updateBasicInfo,
      resetBasicForm,
      updatePassword,
      resetPasswordForm,
      updateNotificationSettings,
      resetNotificationForm,
      getStatusType,
      getPriorityType,
      getProgressStatus
    }
  }
}
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.profile-card {
  margin-bottom: 20px;
}

.profile-header {
  margin-bottom: 20px;
}

.profile-form {
  max-width: 600px;
}

.avatar-uploader {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-upload-btn {
  margin-top: 10px;
}

.tasks-header {
  margin-bottom: 20px;
}
</style>